Skip to content

types refactoring#1683

Merged
Artuomka merged 7 commits intomainfrom
backend_ceadr_refactoring
Mar 24, 2026
Merged

types refactoring#1683
Artuomka merged 7 commits intomainfrom
backend_ceadr_refactoring

Conversation

@Artuomka
Copy link
Copy Markdown
Collaborator

@Artuomka Artuomka commented Mar 23, 2026

Summary by CodeRabbit

  • Bug Fixes

    • Improved error handling consistency across connection operations.
    • Enhanced type safety for connection-related API responses.
  • Refactor

    • Optimized connection parameter handling and validation logic.
    • Made reason and message fields optional when deleting connections, allowing operations to proceed without providing additional details.

Copilot AI review requested due to automatic review settings March 23, 2026 16:20
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 23, 2026

📝 Walkthrough

Walkthrough

The PR refactors the connection entity layer by extracting inline connection parameters into a dedicated data structure, fixing a classname typo, removing UserEntity union types, narrowing enum types, and improving nullability semantics across repositories, DTOs, and use cases. Controller permission methods are updated to return typed data structures, and error handling is improved with explicit unknown types.

Changes

Cohort / File(s) Summary
Data Structure Type Corrections
backend/src/entities/company-info/.../found-company-info.ds.ts, backend/src/entities/company-info/utils/build-found-company-info-ds.ts, backend/src/entities/connection/.../found-connections.ds.ts
Fixed FoundSipleConnectionInfoDS typo to FoundSimpleConnectionInfoDS; removed UserEntity imports and union types; narrowed type fields from ConnectionTypesEnum | string to ConnectionTypesEnum; changed author fields to string.
Connection Parameters Refactoring
backend/src/entities/connection/.../connection-parameters.ds.ts, backend/src/entities/connection/.../create-connection.ds.ts, backend/src/entities/connection/.../update-connection.ds.ts
Extracted new ConnectionParametersDs interface with comprehensive connection configuration fields; refactored CreateConnectionDs and UpdateConnectionDs to reference the new interface instead of inline object types.
DTO Type Narrowing & Schema Updates
backend/src/entities/connection/.../created-connection.dto.ts, backend/src/entities/connection/.../delete-connection.dto.ts
Narrowed CreatedConnectionDTO.type from ConnectionTypesEnum | string to ConnectionTypesEnum; made DeleteConnectionReasonDto fields (reason, message) optional with updated Swagger annotations.
Entity & Repository Layer
backend/src/entities/connection/connection.entity.ts, backend/src/entities/connection/repository/connection.repository.interface.ts, backend/src/entities/connection/repository/custom-connection-repository-extension.ts
Updated ConnectionEntity.type to ConnectionTypesEnum | null and signing_key to string | null; changed repository methods to return Promise<ConnectionEntity | null> instead of non-nullable promises; updated extension type with ThisType<Repository<ConnectionEntity> & IConnectionRepository>.
Controller & Module Updates
backend/src/entities/connection/connection.controller.ts, backend/src/entities/connection/connection.module.ts
Changed permission method return types from IComplexPermission to FoundPermissionsInConnectionDs; removed IComplexPermission import; improved error handling with catch (e: unknown) pattern; updated configure return type to void.
Use Case Refactoring & Type Constraints
backend/src/entities/connection/use-cases/find-all-connections.use.case.ts, backend/src/entities/connection/use-cases/find-one-connection.use.case.ts, backend/src/entities/connection/use-cases/test-connection.use.case.ts, backend/src/entities/connection/use-cases/create-connection.use.case.ts, backend/src/entities/connection/use-cases/find-all-users-in-connection.use.case.ts, backend/src/entities/connection/use-cases/use-cases.interfaces.ts
Narrowed FindAllConnectionsUseCase generic from CreateUserDs | FindUserDs to FindUserDs; improved error handling with e: unknown and safe coercion; added UserWithoutRelations type alias; updated IFindConnections interface to use FindUserDs; improved nullability checks and variable typing.
Utility Function Updates
backend/src/entities/connection/utils/build-created-connection.ds.ts, backend/src/entities/connection/utils/validate-create-connection-data.ts, backend/src/entities/connection/utils/update-connection-entity-for-restoration.ts
Updated buildCreatedConnectionDs to accept nullable token and masterPwd; changed validateConnectionType return from string to boolean; switched updateConnectionEntityForRestoration to use isConnectionTypeAgent(type) instead of entity-level predicate.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

  • Backend ceadr refactoring #1680 — Modifies the same use-case file (find-all-connections.use.case.ts) and connection module wiring, indicating related code-level changes.

Poem

🐰 A typo squashed, parameters extracted clean,
Types now strict—no string shenanigans seen,
Nullable returns flow through each layer bright,
Connections aligned, the refactor feels right! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Security Check ⚠️ Warning The PR introduces security vulnerabilities through nullable type changes without comprehensive null-safety checks, unsafe type casts bypassing security-critical fields, and conditional encryption logic that could expose credentials when masterPwd/token are null. Add immediate null checks after nullable repository method calls, replace unsafe 'null as unknown as' casts with proper object construction, verify all validateConnectionType callers handle boolean returns, ensure signing_key null has verification fallback, and audit masterPwd/token null-coalescing in encryption logic.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'types refactoring' accurately reflects the primary objective of the pull request, which involves extensive TypeScript type improvements, narrowing, and refactoring across multiple entity data structures and utilities throughout the connection and company-info modules.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch backend_ceadr_refactoring

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR refactors connection-related TypeScript types across the backend to reduce unsafe casts, improve nullability correctness, and align DTOs/entities/use-cases with shared ConnectionTypesEnum.

Changes:

  • Introduces a shared ConnectionParametersDs type and wires it into create/update connection data structures.
  • Tightens/clarifies types across repositories, entities, DTOs, and use-cases (e.g., unknown catches, ConnectionTypesEnum usage, nullable returns).
  • Renames a misspelled DS type (FoundSipleConnectionInfoDSFoundSimpleConnectionInfoDS) and propagates the rename.

Reviewed changes

Copilot reviewed 22 out of 22 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
backend/src/entities/connection/utils/validate-create-connection-data.ts Makes validateConnectionType return a boolean consistently.
backend/src/entities/connection/utils/update-connection-entity-for-restoration.ts Switches agent-check helper to a type-based predicate.
backend/src/entities/connection/utils/build-created-connection.ds.ts Allows nullable/optional token and masterPwd inputs.
backend/src/entities/connection/use-cases/use-cases.interfaces.ts Updates IFindConnections.execute to accept FindUserDs instead of CreateUserDs.
backend/src/entities/connection/use-cases/test-connection.use.case.ts Improves error typing/formatting; adjusts AWS-processing call sites (currently via unsafe cast).
backend/src/entities/connection/use-cases/find-one-connection.use.case.ts Types caught exceptions as unknown.
backend/src/entities/connection/use-cases/find-all-users-in-connection.use.case.ts Adds a relation-omitting user type alias; still relies on a cast for DTO building.
backend/src/entities/connection/use-cases/find-all-connections.use.case.ts Narrows generic input to FindUserDs only.
backend/src/entities/connection/use-cases/create-connection.use.case.ts Makes connectionCopy nullable and guards its usage in finally.
backend/src/entities/connection/repository/custom-connection-repository-extension.ts Improves this typing for repository extension; makes several fetches nullable.
backend/src/entities/connection/repository/connection.repository.interface.ts Updates signatures (string param types + nullable return types).
backend/src/entities/connection/connection.module.ts Refines configure return type to void.
backend/src/entities/connection/connection.entity.ts Types type as `ConnectionTypesEnum
backend/src/entities/connection/connection.controller.ts Removes unused permission interface import; tightens local typings and return types.
backend/src/entities/connection/application/dto/delete-connection.dto.ts Makes reason/message optional and updates Swagger metadata accordingly.
backend/src/entities/connection/application/dto/created-connection.dto.ts Restricts type to ConnectionTypesEnum only.
backend/src/entities/connection/application/data-structures/update-connection.ds.ts Replaces inline connection_parameters shape with ConnectionParametersDs.
backend/src/entities/connection/application/data-structures/found-connections.ds.ts Tightens types (esp. type/author) and fixes DS naming typo.
backend/src/entities/connection/application/data-structures/create-connection.ds.ts Replaces inline connection_parameters shape with ConnectionParametersDs.
backend/src/entities/connection/application/data-structures/connection-parameters.ds.ts Adds the shared connection-parameters interface.
backend/src/entities/company-info/utils/build-found-company-info-ds.ts Updates imports/usages for renamed FoundSimpleConnectionInfoDS.
backend/src/entities/company-info/application/data-structures/found-company-info.ds.ts Updates imports/usages for renamed FoundSimpleConnectionInfoDS.
Comments suppressed due to low confidence (1)

backend/src/entities/connection/application/data-structures/create-connection.ds.ts:8

  • CreateConnectionDs now depends on ConnectionParametersDs, where most fields are optional. This significantly weakens compile-time guarantees compared to the previous inline type for create flows (e.g., host/port/username can be omitted without a type error). Consider splitting into separate parameter types for create vs update (required vs partial) or using Required<...> for the fields that must be present during creation.
export class CreateConnectionDs {
	connection_parameters: ConnectionParametersDs;
	creation_info: {
		authorId: string;
		masterPwd: string;
	};

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

removeConnection(connection: ConnectionEntity): Promise<ConnectionEntity>;

findConnectionWithGroups(connectionId: string): Promise<ConnectionEntity>;
findConnectionWithGroups(connectionId: string): Promise<ConnectionEntity | null>;
Copy link

Copilot AI Mar 23, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The repository contract was changed to allow null returns (e.g., findConnectionWithGroups). At least some call sites assume a non-null connection and immediately dereference (e.g., CreateGroupInConnectionUseCase uses .groups without a null check). Either keep these methods non-null and throw on missing records, or update all callers to handle null explicitly to avoid runtime crashes.

Suggested change
findConnectionWithGroups(connectionId: string): Promise<ConnectionEntity | null>;
findConnectionWithGroups(connectionId: string): Promise<ConnectionEntity>;

Copilot uses AI. Check for mistakes.
Comment on lines 112 to 115
const dataForProcessing: CreateConnectionDs = {
connection_parameters: updated,
creation_info: null,
creation_info: null as unknown as CreateConnectionDs['creation_info'],
};
Copy link

Copilot AI Mar 23, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

processAWSConnection only uses connection_parameters, but this use case is now passing creation_info via null as unknown as ..., which masks a real type mismatch and can hide future bugs. Consider changing processAWSConnection to accept a narrower type (e.g., { connection_parameters: ... }) or making CreateConnectionDs['creation_info'] optional/nullable so callers don't need an unsafe cast.

Copilot uses AI. Check for mistakes.
const dataForProcessing: CreateConnectionDs = {
connection_parameters: connectionData,
creation_info: null,
creation_info: null as unknown as CreateConnectionDs['creation_info'],
Copy link

Copilot AI Mar 23, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same issue as above: creation_info is forced to null via a double cast. It would be safer to adjust the processAWSConnection/CreateConnectionDs types so this call site can pass a correctly typed object without as unknown as ....

Suggested change
creation_info: null as unknown as CreateConnectionDs['creation_info'],
creation_info: null as CreateConnectionDs['creation_info'],

Copilot uses AI. Check for mistakes.
Comment on lines +25 to 28
const userInConnection: UserWithoutRelations[] =
await this._dbContext.userRepository.findAllUsersInConnection(connectionId);
return userInConnection.map((user) => buildFoundUserDto(user as UserEntity));
}
Copy link

Copilot AI Mar 23, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

UserWithoutRelations is introduced to improve typing, but the user as UserEntity cast reintroduces an unchecked assumption and defeats the benefit. Since buildFoundUserDto only needs scalar fields, consider widening its parameter type (e.g., Pick<UserEntity, ...>) so this mapping can be done without a cast.

Copilot uses AI. Check for mistakes.
Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
backend/src/entities/company-info/utils/build-found-company-info-ds.ts (1)

29-47: ⚠️ Potential issue | 🟡 Minor

Missing type field in connection mapping.

The FoundSimpleConnectionInfoDS type includes a type?: ConnectionTypesEnum property (per found-connections.ds.ts lines 144-145), but the mapping here doesn't include it. If this field should be populated from connection.type, it's missing.

Proposed fix to include type field
 const connectionsRO: Array<FoundSimpleConnectionInfoDS> = companyInfoFromCore.connections.map((connection) => {
   return {
     id: connection.id,
     createdAt: connection.createdAt,
     updatedAt: connection.updatedAt,
     title: connection.title,
+    type: connection.type,
     isTestConnection: connection.isTestConnection,
     author: buildSimpleUserInfoDs(connection.author),
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/src/entities/company-info/utils/build-found-company-info-ds.ts`
around lines 29 - 47, The mapping that builds connectionsRO for
companyInfoFromCore.connections is missing the optional `type` property defined
on FoundSimpleConnectionInfoDS; update the object returned in the map (inside
the connectionsRO creation) to include `type: connection.type` so each
connection entry includes ConnectionTypesEnum when present, ensuring other
fields (id, createdAt, updatedAt, title, isTestConnection, author via
buildSimpleUserInfoDs, and groups) remain unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@backend/src/entities/connection/use-cases/test-connection.use.case.ts`:
- Around line 112-115: The code constructs dataForProcessing: CreateConnectionDs
with creation_info set via an unsafe cast (null as unknown as ...); instead
build and pass a real creation_info object using the available
inputData.update_info fields (e.g. inputData.update_info.authorId and
inputData.update_info.masterPwd) and any other required properties for
CreateConnectionDs.creation_info, replacing the null cast in dataForProcessing
(and the similar instance at lines ~144-147) so the type system is satisfied and
no unsafe cast is used.

---

Outside diff comments:
In `@backend/src/entities/company-info/utils/build-found-company-info-ds.ts`:
- Around line 29-47: The mapping that builds connectionsRO for
companyInfoFromCore.connections is missing the optional `type` property defined
on FoundSimpleConnectionInfoDS; update the object returned in the map (inside
the connectionsRO creation) to include `type: connection.type` so each
connection entry includes ConnectionTypesEnum when present, ensuring other
fields (id, createdAt, updatedAt, title, isTestConnection, author via
buildSimpleUserInfoDs, and groups) remain unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a831b1fc-f2d9-4ddd-98f8-f7d0e864e4ef

📥 Commits

Reviewing files that changed from the base of the PR and between b5734ed and f7721da.

📒 Files selected for processing (22)
  • backend/src/entities/company-info/application/data-structures/found-company-info.ds.ts
  • backend/src/entities/company-info/utils/build-found-company-info-ds.ts
  • backend/src/entities/connection/application/data-structures/connection-parameters.ds.ts
  • backend/src/entities/connection/application/data-structures/create-connection.ds.ts
  • backend/src/entities/connection/application/data-structures/found-connections.ds.ts
  • backend/src/entities/connection/application/data-structures/update-connection.ds.ts
  • backend/src/entities/connection/application/dto/created-connection.dto.ts
  • backend/src/entities/connection/application/dto/delete-connection.dto.ts
  • backend/src/entities/connection/connection.controller.ts
  • backend/src/entities/connection/connection.entity.ts
  • backend/src/entities/connection/connection.module.ts
  • backend/src/entities/connection/repository/connection.repository.interface.ts
  • backend/src/entities/connection/repository/custom-connection-repository-extension.ts
  • backend/src/entities/connection/use-cases/create-connection.use.case.ts
  • backend/src/entities/connection/use-cases/find-all-connections.use.case.ts
  • backend/src/entities/connection/use-cases/find-all-users-in-connection.use.case.ts
  • backend/src/entities/connection/use-cases/find-one-connection.use.case.ts
  • backend/src/entities/connection/use-cases/test-connection.use.case.ts
  • backend/src/entities/connection/use-cases/use-cases.interfaces.ts
  • backend/src/entities/connection/utils/build-created-connection.ds.ts
  • backend/src/entities/connection/utils/update-connection-entity-for-restoration.ts
  • backend/src/entities/connection/utils/validate-create-connection-data.ts

Comment on lines 112 to 115
const dataForProcessing: CreateConnectionDs = {
connection_parameters: updated,
creation_info: null,
creation_info: null as unknown as CreateConnectionDs['creation_info'],
};
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify whether processAWSConnection currently reads creation_info fields.
fd process-aws-connection.util.ts --exec sed -n '1,220p' {}
rg -n -C3 '\bcreation_info\b|\bauthorId\b|\bmasterPwd\b' backend/src/entities/connection/utils/process-aws-connection.util.ts

Repository: rocket-admin/rocketadmin

Length of output: 1693


🏁 Script executed:

cat -n backend/src/entities/connection/use-cases/test-connection.use.case.ts | sed -n '100,160p'

Repository: rocket-admin/rocketadmin

Length of output: 2296


🏁 Script executed:

rg -n "CreateConnectionDs" backend/src/entities/connection/application/data-structures/ -A 15

Repository: rocket-admin/rocketadmin

Length of output: 816


🏁 Script executed:

rg -n "creation_info" backend/src/entities/connection/ --type ts -B 2 -A 2 | head -100

Repository: rocket-admin/rocketadmin

Length of output: 5040


🏁 Script executed:

cat -n backend/src/entities/connection/use-cases/test-connection.use.case.ts | sed -n '1,50p'

Repository: rocket-admin/rocketadmin

Length of output: 2639


🏁 Script executed:

rg -n "TestConnectionInputData\|TestConnectionDs\|interface.*Test.*Connection" backend/src/entities/connection/ -B 2 -A 10 --type ts

Repository: rocket-admin/rocketadmin

Length of output: 50


🏁 Script executed:

cat -n backend/src/entities/connection/use-cases/test-connection.use.case.ts | sed -n '160,180p'

Repository: rocket-admin/rocketadmin

Length of output: 1017


🏁 Script executed:

rg -n "class UpdateConnectionDs\|export.*UpdateConnectionDs" backend/src/entities/connection/ -A 10 --type ts

Repository: rocket-admin/rocketadmin

Length of output: 50


🏁 Script executed:

cat -n backend/src/entities/connection/use-cases/test-connection.use.case.ts | sed -n '35,50p'

Repository: rocket-admin/rocketadmin

Length of output: 663


🏁 Script executed:

fd "update-connection.ds.ts" backend/src/entities/connection/ --exec cat -n {}

Repository: rocket-admin/rocketadmin

Length of output: 379


🏁 Script executed:

fd "*.ts" backend/src/entities/connection/application/data-structures/ --exec basename {} \; | sort

Repository: rocket-admin/rocketadmin

Length of output: 351


Avoid null as unknown as for required creation_info.

Lines 114 and 146 bypass the type system with unsafe casts. Since inputData.update_info.authorId and inputData.update_info.masterPwd are available, pass a real creation_info object instead:

Suggested patch
 				const dataForProcessing: CreateConnectionDs = {
 					connection_parameters: updated,
-					creation_info: null as unknown as CreateConnectionDs['creation_info'],
+					creation_info: {
+						authorId: inputData.update_info.authorId,
+						masterPwd: inputData.update_info.masterPwd,
+					},
 				};
@@
 			const dataForProcessing: CreateConnectionDs = {
 				connection_parameters: connectionData,
-				creation_info: null as unknown as CreateConnectionDs['creation_info'],
+				creation_info: {
+					authorId: inputData.update_info.authorId,
+					masterPwd: inputData.update_info.masterPwd,
+				},
 			};

Also applies to: 144-147

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/src/entities/connection/use-cases/test-connection.use.case.ts` around
lines 112 - 115, The code constructs dataForProcessing: CreateConnectionDs with
creation_info set via an unsafe cast (null as unknown as ...); instead build and
pass a real creation_info object using the available inputData.update_info
fields (e.g. inputData.update_info.authorId and inputData.update_info.masterPwd)
and any other required properties for CreateConnectionDs.creation_info,
replacing the null cast in dataForProcessing (and the similar instance at lines
~144-147) so the type system is satisfied and no unsafe cast is used.

@Artuomka Artuomka merged commit c021a6e into main Mar 24, 2026
17 of 19 checks passed
@Artuomka Artuomka deleted the backend_ceadr_refactoring branch March 24, 2026 09:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants